module.exports = function ($scope, $state, code, group_code, saleinfo, goodlist, infolist, type, $resource, 
	sale_code, toaster, getattrbycode, usersubsibyquery, signup, $modalInstance) {
		
	$scope.type = type;
	$scope.sale_code = sale_code;

	$scope.num = 1;

	//人员数组
	$scope.objs = [];

	//销售品编号
	var sale_code = '';

	//人员补贴（key：电话，value：补贴额)
	var allsubsidy = {};

	//商品可用补贴额
	var goodssubsidy = 0;

	//商品信息（key：编号，value：价格)
	var goods = {};

	//普通商品编号
	var goodscode = '';
	var payprice = '0';

	//政府补贴商品编号
	var goodscodegov = '';
	var paypricegov = '0';

	//预定人数全局变量
	var count = 1;

	//总价
	$scope.totalprice = 0;

	//添加人员
	$scope.add = function () {
		var num = $scope.num;
		if (!angular.isNumber(num)) {
			alert('请输入数字');
			return;
		}
		row(num);
	};



	//初始化 商品列表
	goodlist.get({ 'code': code }, function (res) {
		if (res.errcode === 0) {
			$scope.bookingnotes = res.data[0].bookingnotes;
			$scope.goodarr = res.data;
			for (var i = 0; i < res.data.length; i++) {
				var tmp = res.data[i];
				if (i === 0) sale_code = tmp.sale_code;
				// if(tmp.type_attr === '98')
				// {
				// 	//补贴额
				// 	goodssubsidy = tmp.govsubsidy_price;
				// 	goodscodegov = tmp.goods_code;
				// 	paypricegov = tmp.cost_price - tmp.govsubsidy_price;
				// 	goods[goodscodegov] = paypricegov;
				// }
				// else
				// {
				goodscode = tmp.goods_code;
				payprice = tmp.cost_price;
				goods[goodscode] = payprice;
				// }
			}
		} else {
			alert(res.errmsg);
		}
	});

	//删除信息
	$scope.del = function (index) {
		$scope.objs.splice(index, 1);
		calctotalprice();
	};


	//gogogogoogogo
	$scope.go = function () {
		$scope.cardnoMap = {};
		for (let index = 0; index < $scope.objs.length; index++) {
			const element = $scope.objs[index];
			if($scope.type == 'F95' && element.check_status == 0){
				toaster.warning({title: '', body: '检验未完成,无法提交'})
				return false;
			}
			if(element.cardno){
				if (!checkCardNo(element.cardno)) {
					toaster.warning({title: '', body: element.name+'的身份证：【' + element.cardno + '】格式错误'})
					return false;
				} else if ($scope.cardnoMap[element.cardno] === undefined) {
					$scope.cardnoMap[element.cardno] = 1;
				} else {
					toaster.warning({title: '', body: '身份证：【' + element.cardno + '】重复'});
					return false;
				}
			}
		}
		//检查infolist
		var msg = '';
		for (var i = 0; i < $scope.objs.length; i++) {
			var tmp = $scope.objs[i];
			if (tmp.goods_code === '') {
				$scope.objs.splice(i, 1);
				i--;
				continue;
			}
			msg += '电话:' + tmp.mobile + ',姓名:' + tmp.name + ',身份证:' + tmp.cardno + '\r\n';
		}
		msg = '报名信息确认\r\n' + msg + '\r\n\r\n总计' + $scope.totalprice * 0.01 + '元';
		if (!confirm(msg)) {
			return;
		}

		var para = {
			'infolist': $scope.objs,
			'order_code': code,
			'sale_code': sale_code,
			'group_code': group_code,
			'all_price': $scope.totalprice
		};
		signup.save(para, function (res) {
			if (res.errcode === 0) {
				alert("提交成功");
				$modalInstance.close();
			} else {
				alert(res.errmsg);
			}
		});
	};

	//获取补贴信息
	function getsubsiby(obj) {
		usersubsibyquery.get({ 'mobile': obj.mobile }, function (res) {
			if (res.errcode === 0) {
				if (res.data.isexis === '0') {
					if (obj.disabled) {
						obj.disabled = false;
						obj.name = '';
						obj.cardno = '';
						obj.subsidy = 0;
					}
				} else {
					obj.name = res.data.username;
					obj.cardno = res.data.papersno;
					obj.disabled = true;
					obj.subsidy = res.data.generalsubsidy;
					allsubsidy[obj.mobile] = res.data.generalsubsidy;
				}
			}
			choosegoods(obj, 1);
		});
	}

	//根据游客政府补贴选择商品，
	//what : 1,手动选择商品
	//有补贴可以选择非补贴商品
	//无补贴不可以选择补贴商品
	function choosegoods(obj, what) {
		//游客电话
		var mobile = obj.mobile;
		//游客补贴
		var subsidy = allsubsidy[mobile] || 0;

		//手动
		if (what == 1) {
			if (subsidy < goodssubsidy) {
				obj.goods_code = goodscode;
				obj.pay_price = payprice;
				obj.usesubsidy = 0;
			}
		} else {
			if (subsidy >= goodssubsidy) {
				obj.goods_code = goodscodegov;
				obj.pay_price = paypricegov;
				obj.usesubsidy = goodssubsidy;
			}
			//不可以用补贴
			else {
				obj.goods_code = goodscode;
				obj.pay_price = payprice;
				obj.usesubsidy = 0;
			}
		}

		//手动改变下来，修改价格
		if (what == 1) {
			for (var i = 0, j = $scope.goodarr.length; i < j; i++) {
				var tt = $scope.goodarr[i];
				if (tt.goods_code == obj.goods_code) {
					if (tt.type_attr === '98') {
						obj.pay_price = tt.cost_price - tt.govsubsidy_price;
						obj.usesubsidy = tt.govsubsidy_price;
					} else {
						obj.pay_price = tt.cost_price;
						obj.usesubsidy = '0';
					}
					break;
				}
			}
		}
		calctotalprice();
	}

	//计算总价
	function calctotalprice() {
		$scope.totalprice = 0;
		for (var i = 0, j = $scope.objs.length; i < j; i++) {
			var tmp = $scope.objs[i];
			if (tmp.goods_code == '') continue;
			$scope.totalprice += parseInt(goods[tmp.goods_code]);
		}
	}

	$scope.cancel = function () {
		$modalInstance.close();
	}

	//添加一行
	function row(num) {
		var j, gCode = $scope.goodarr[0].goods_code;
		for (var i = 1; i <= num; i++) {
			j = parseInt(count);
			var obj = {
				'name': '第' + j + '人',
				'mobile': '',
				'cardno': '',
				'goods_code': gCode,
				'pay_price': goods[gCode],	//实际支付价格
				'card_type': '1',
				'subsidy': 0,		//补贴余额
				'usesubsidy': 0,	//本次使用补贴
				'disabled': false,
				'subsidy_status': 0,
				'check_status': 1
			};
			count += 1;
			if ($scope.type == 'F95') {
				$scope.check2(obj)
			}
			$scope.objs.push(obj);
		}
		calctotalprice();
	}

	$scope.export = function () {
		var event = document.getElementById('excel');
		if (event.files[0].name.indexOf(".xls") < 0) {
			toaster.error({ title: '', body: '文件格式不正确' });
			return;
		}

		var reader = new FileReader();
		reader.onload = function (e) {
			var data = e.target.result;
			data = String.fromCharCode.apply(null, new Uint8Array(data));
			$scope.parseToJson(XLSX.read(btoa(data), { type: 'base64' }));
		};
		reader.readAsArrayBuffer(event.files[0]);
	}

	//excel读取之后,解析内容
	$scope.parseToJson = function (workbook) {
		var title = { 'smart_card_no': workbook.Strings[0].h, 'smart_card': workbook.Strings[1].h };
		// 暂时只能读取第一个sheet页的数据
		var sheet1Date = workbook.Sheets[workbook.SheetNames[0]];
		var card_list = XLSX.utils.sheet_to_row_object_array(sheet1Date);

		$scope.list = card_list;
		for (let index = 0; index < $scope.list.length; index++) {
			const element = $scope.list[index];
			for (const key in element) {
				if (element.hasOwnProperty(key)) {
					const oneMap = element[key];
					element[key] = oneMap.replace(/\s+/g, "");//去空格
				}
			}
		}
		row_new();
	}

	function row_new() {
		var gCode = $scope.goodarr[0].goods_code;
		let index = $scope.objs.length;
		for (let index = 0; index < $scope.list.length; index++) {
			const element = $scope.list[index];
			var obj = {
				'name': element.name,
				'mobile': element.mobile,
				'cardno': element.cardno,
				'goods_code': gCode,
				'pay_price': goods[gCode],	//实际支付价格
				'card_type': '1',
				'subsidy': 0,		//补贴余额
				'usesubsidy': 0,	//本次使用补贴
				'disabled': false,
				'subsidy_status': 0,
				'check_status': 1
			};
			if ($scope.type == 'F95') {
				$scope.check2(obj)
			}
			$scope.objs.push(obj);
		}
		$scope.check(index);
		calctotalprice();
		$scope.$apply();
	}

	$scope.check = function(index) {
		if (index >= $scope.objs.length || $scope.type != 'F95') {
			return false;
		}
		let obj = $scope.objs[index];
		if(!obj.cardno){
			obj.msg = '未填写身份证';
			$scope.check(++index);
			return false;
		}
		obj.subsidy_status = 0;
		if (!obj.name) {
			obj.msg = '失败：请填写姓名';
			$scope.check(++index);
			return false;
		}
		if (!obj.mobile) {
			obj.msg = '失败：请填写手机号';
			return false;
		}
		if (!checkCardNo(obj.cardno)) {
			obj.msg = '失败：身份证信息有误';
			$scope.check(++index);
			return false;
		}
		var para = {
			'cardno': obj.cardno,
			'name': obj.name,
			'mobile': obj.mobile,
			'subsidy_id': "2018HMLYSubsidy"
		}
		obj.num = 1;
		obj.sale_code = $scope.sale_code;
		obj.check_status = 0;
		obj.subsidy_num = 0;
		$resource('/api/ac/puc/pubSubsidyFXDService/getSubsidyUserInfoByCardno', {}, {}).save(para, function (res) {
			if (res.errcode === 0) {
				obj.subsidy_status = 1;
				obj.usesubsidy = (res.data.subsidy_num>saleinfo.subsidy_fee?saleinfo.subsidy_fee:res.data.subsidy_num)/100;
				obj.msg = '剩余补贴余额：' + res.data.subsidy_num / 100;
			} else {
				obj.msg = '失败：不符合补贴条件';
			}
			obj.check_status = 1;
			$scope.check(++index);
		});
	}

	$scope.check2 = function(obj) {
		if(!obj.cardno){
			obj.msg = '未填写身份证';
			return;
		}
		obj.subsidy_status = 0;
		if (!obj.name) {
			obj.msg = '失败：请填写姓名';
			return false;
		}
		if (!obj.mobile) {
			obj.msg = '失败：请填写手机号';
			return false;
		}
		if (!checkCardNo(obj.cardno)) {
			obj.msg = '失败：身份证信息有误';
			return false;
		}
		var para = {
			'cardno': obj.cardno,
			'name': obj.name,
			'mobile': obj.mobile,
			'subsidy_id': "2018HMLYSubsidy"
		}
		
		obj.num = 1;
		obj.sale_code = $scope.sale_code;
		obj.check_status = 0;
		///api/ac/tc/ticketOrderService/checkOrderSubsidy
		$resource('/api/ac/puc/pubSubsidyFXDService/getSubsidyUserInfoByCardno', {}, {}).save(para, function (res) {
			if (res.errcode === 0) {
				obj.subsidy_status = 1;
				obj.usesubsidy = (res.data.subsidy_num>saleinfo.subsidy_fee?saleinfo.subsidy_fee:res.data.subsidy_num)/100;
				obj.msg = '剩余补贴余额：' + res.data.subsidy_num / 100;
			} else {
				obj.msg = res.errmsg;
			}
			obj.check_status = 1;
		});
	}


	/**
	 * 验证手机号
	 * @param {需要校验的手机号} mobile
	 * @return 错误返回 false , 正确返回 true
	 */
	function isMobil(mobile) {
		var patrn = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
		if (!patrn.exec(mobile)) {
			return false;
		}
		return true;
	}

	var checkCardNo = function (code) {

		var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
		var tip = "";
		var pass = true;

		if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
			tip = "身份证号格式错误";
			pass = false;
		}

		else if (!city[code.substr(0, 2)]) {
			tip = "身份证地址编码错误";
			pass = false;
		}
		else {
			//18位身份证需要验证最后一位校验位
			if (code.length == 18) {
				code = code.split('');
				//加权因子
				var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
				//校验位
				var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
				var sum = 0;
				var ai = 0;
				var wi = 0;
				for (var i = 0; i < 17; i++) {
					ai = code[i];
					wi = factor[i];
					sum += ai * wi;
				}
				var last = parity[sum % 11];
				if (parity[sum % 11] != code[17]) {
					tip = "身份证校验位错误";
					pass = false;
				}
			}
		}
		return pass;

	}

};
